package com.hly.service;

import com.hly.config.ExceptionConfig;
import com.hly.dao.ICartsDao;
import com.hly.dao.IOrdersDao;
import com.hly.dao.IitemsDao;
import com.hly.model.Carts;
import com.hly.model.Items;
import com.hly.model.Orders;
import com.hly.model.Users;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @program: hly_emall_ssm
 * Author HLY
 * @desc
 * @create: 2020-10-12 11:10
 **/
@Service
public class OrdersService {
    @Autowired
    private IOrdersDao dao;
    @Autowired
    private IitemsDao iitemsDao;
    @Autowired
    private ICartsDao iCartsDao;
    @Resource
    private CartsService cartsService;
    @Resource
    private GoodsService goodsService;

    public Integer save(Integer userId) throws ExceptionConfig.MyException {
        List<Carts> cartsList = cartsService.getList(userId);
        System.out.println("cartsList.size() = "+cartsList.size());
        if(Objects.nonNull(cartsList) || cartsList.isEmpty()){
            throw new ExceptionConfig.MyException("没有商品！");
        }
        for (Carts cart:cartsList
             ) {
            if(cart.getGood().getStock() <  cart.getAmount()){
                throw new ExceptionConfig.MyException(cart.getGood().getName()+"库存不足！");
            }
            goodsService.updateStock(cart.getGood().getId() , cart.getAmount()); //减少库存
            goodsService.updateSales(cart.getGood().getId() , cart.getAmount());//增加销量
        }
        int total = 0;
        for (Carts cart:cartsList
             ) {
            total += cart.getGood().getPrice()*cart.getAmount();
        }
        Orders orders = new Orders();
        orders.setUserId(userId);
        orders.setTotal(total);
        orders.setStatus(Orders.STATUS_UNPAY);
        orders.setAmount(cartsList.size());
        orders.setSystime(new Date());
        dao.insertOrder(orders);
        int orderId = orders.getId();
        System.out.println("orderId = "+orderId);
        //添加订单项
        for (Carts cart:cartsList
             ) {
            Items items = new Items();
            items.setOrderId(orderId);
            items.setGoodId(cart.getGoodId());
            items.setAmount(cart.getAmount());
            items.setPrice(cart.getGood().getPrice());
            iitemsDao.insertItems(items);
        }
        //清空购物车
        iCartsDao.clean(userId);
        return orderId;
    }
}
